package com.example.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.client.InformationClient;
import com.example.common.Result;
import com.example.dao.BorrowDao;
import com.example.domain.Borrow;
import com.example.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class BorrowService {

    @Autowired
    private BorrowDao borrowDao;
    @Autowired
    private InformationClient informationClient;

    public void addBorrow(Date begin, Date end, Long userId,Long bookId,String bookName){
        Borrow borrow = new Borrow();
        borrow.setBookId(bookId);
        borrow.setUserId(userId);
        borrow.setBookName(bookName);
        borrow.setTimeStart(begin);
        borrow.setTimeEnd(end);
//        计算日期的相差天数
        Integer length = DateUtils.daysBetween(end, begin);
        borrow.setTimeLength(length);
        borrowDao.insert(borrow);
    }

    public void updateStatus(Long userId){
        List<Borrow> list = selectAllByUserId(userId);
        for(int i=0;i<list.size();i++){
            Borrow borrow = list.get(i);
            Date end = borrow.getTimeEnd();
            Date now = new Date();

            //        计算日期的相差天数
            Integer length = DateUtils.daysBetween(end, now);
            if(length<0&&borrow.getStatus()==0){
                borrow.setStatus(2);
                borrowDao.updateById(borrow);
            }
        }
    }

    public List<Borrow> selectAllByUserId(Long userId){
        QueryWrapper<Borrow> qw = new QueryWrapper<>();
        qw.eq("userId",userId);
        return borrowDao.selectList(qw);
    }

    /*
    还书，逾期扣积分，期内加积分（积分操作远程调用）
     */
    public Result returnBook(Borrow borrow){
        Integer downPoints = 0;
        if(borrow.getStatus()==2){
            downPoints = informationClient.downPoints(borrow);
        }

        borrow.setStatus(1);
        borrowDao.updateById(borrow);
        if(downPoints!=0){
            return Result.warning("逾期还书，已扣除积分"+ downPoints + "，积分为零将不能借书，请及时还书");
        }
        informationClient.upPoints(borrow);
        return Result.success("还书成功,增加1积分");
    }
}
